﻿//
// *************************************************************************************
// WP-Framework
//
// Developed by 
// Lukas Kretschmar (lkretschmar.dev@bluewin.ch)
//
// Switzerland, Copyright (c) 2013 lkretschmar
// This content is released under the MIT License (http://opensource.org/licenses/MIT).
//     
// *************************************************************************************
//
//


using System.Linq.Expressions;
using System.Collections.Generic;
using System.Linq;
using KretschIT.WP_Fx.EasyMoq.Calls.Collections.Items;

namespace KretschIT.WP_Fx.EasyMoq.Calls.Collections
{
    internal class CallCollection<TItem> : ICallCollection<TItem> where TItem : class, ICallItem
    {
        private readonly List<TItem> items = new List<TItem>();

        public void Add(TItem item)
        {
            if (IsInvalidItem(item) || Contains(item))
            {
                return;
            }
            this.items.Add(item);
        }

        private static bool IsInvalidItem(TItem item)
        {
            return item == null;
        }
        
        private bool Contains(TItem item)
        {
            return this.items.Any(i => i.Id == item.Id);
        }

        public TItem Get(MethodCallExpression call)
        {
            if (this.IsInvalidCall(call))
            {
                return null;
            }
            return this.GetItem(call);
        }

        private bool IsInvalidCall(MethodCallExpression call)
        {
            return call == null;
        }

        private TItem GetItem(MethodCallExpression call)
        {
            return this.items.FirstOrDefault(i => i.Matches(call));
        }

        public IEnumerable<TItem> GetMatches(MethodCallExpression call)
        {
            return this.items.Where(i => i.Matches(call)).ToList();
        }

        public int Count
        {
            get
            {
                return this.items.Count;
            }
        }

    }
}
